#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialogconfig.h"
#include <QMessageBox>
#include <QTableWidgetItem>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    addActions();

    connect(&m_device,SIGNAL(DataReady()),this,SLOT(onObtain()));

    m_device.setParent(this);
    if(!m_device.open("COM5"))
        QMessageBox::critical(this,"Error","Can not open the port");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::addActions()
{
    QAction *a;

    a=ui->mainToolBar->addAction("Obtener");
    connect(a, SIGNAL(triggered()), &m_device, SLOT(Obtain()));

    a=ui->mainToolBar->addAction("Guardar");
    connect(a, SIGNAL(triggered()), this, SLOT(onSave()));

    a=ui->mainToolBar->addAction("Configurar");
    connect(a, SIGNAL(triggered()), this, SLOT(onConfig()));


}

void MainWindow::onSave()
{
}

void MainWindow::onObtain()
{
    QTableWidgetItem *item;
    int row=ui->tableWidget->rowCount();

    MeasureList::const_iterator it=m_device.measureList().begin();

    for(;it!=m_device.measureList().end(); it++)
    {
        ui->tableWidget->insertRow(row);
        measure_t m=(*it);

        item=new QTableWidgetItem("DATE");
        ui->tableWidget->setItem(row,0,item);

        item=new QTableWidgetItem(QString::number((double)m.temperature));
        ui->tableWidget->setItem(row,1,item);

        item=new QTableWidgetItem(QString::number((double)m.speed));
        ui->tableWidget->setItem(row,2,item);

        item=new QTableWidgetItem(QString::number(m.direction));
        ui->tableWidget->setItem(row,3,item);


    }


    QMessageBox::information(this,"Information","Data Readdy");
}

void MainWindow::onConfig()
{
    DialogConfig d;
    if(d.exec()== QDialog::Accepted)
        m_device.SetConfig(d.dateTime(),d.refreshTime()*60);

}
